(function ($) {
  // USE STRICT
  "use strict";
  var navbars = ['header', 'aside'];
  var hrefSelector = 'a:not([target="_blank"]):not([href^="#"]):not([class^="chosen-single"])';
  var linkElement = navbars.map(element => element + ' ' + hrefSelector).join(', ');
  $(".animsition").animsition({
    inClass: 'zoom-in-sm',
    outClass: 'zoom-out-sm',
    inDuration: 300,
    outDuration: 300,
    linkElement: linkElement,
    loading: true,
    loadingParentElement: 'html',
    loadingClass: 'page-loader',
    loadingInner: '<div class="page-loader__spin"></div>',
    timeout: false,
    timeoutCountdown: 5000,
    onLoadEvent: true,
    browser: ['animation-duration', '-webkit-animation-duration'],
    overlay: false,
    overlayClass: 'animsition-overlay-slide',
    overlayParentElement: 'html',
    transition: function (url) {
      window.location.href = url;
    }
  });


})(jQuery);
(function ($) {
  // USE STRICT
  "use strict";

  // Map
  try {

    var vmap = $('#vmap');
    if (vmap[0]) {
      vmap.vectorMap({
        map: 'world_en',
        backgroundColor: null,
        color: '#ffffff',
        hoverOpacity: 0.7,
        selectedColor: '#1de9b6',
        enableZoom: true,
        showTooltip: true,
        values: sample_data,
        scaleColors: ['#1de9b6', '#03a9f5'],
        normalizeFunction: 'polynomial'
      });
    }

  } catch (error) {
    console.log(error);
  }

  // Europe Map
  try {

    var vmap1 = $('#vmap1');
    if (vmap1[0]) {
      vmap1.vectorMap({
        map: 'europe_en',
        color: '#007BFF',
        borderColor: '#fff',
        backgroundColor: '#fff',
        enableZoom: true,
        showTooltip: true
      });
    }

  } catch (error) {
    console.log(error);
  }

  // USA Map
  try {

    var vmap2 = $('#vmap2');

    if (vmap2[0]) {
      vmap2.vectorMap({
        map: 'usa_en',
        color: '#007BFF',
        borderColor: '#fff',
        backgroundColor: '#fff',
        enableZoom: true,
        showTooltip: true,
        selectedColor: null,
        hoverColor: null,
        colors: {
          mo: '#001BFF',
          fl: '#001BFF',
          or: '#001BFF'
        },
        onRegionClick: function (event, code, region) {
          event.preventDefault();
        }
      });
    }

  } catch (error) {
    console.log(error);
  }

  // Germany Map
  try {

    var vmap3 = $('#vmap3');
    if (vmap3[0]) {
      vmap3.vectorMap({
        map: 'germany_en',
        color: '#007BFF',
        borderColor: '#fff',
        backgroundColor: '#fff',
        onRegionClick: function (element, code, region) {
          var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();

          alert(message);
        }
      });
    }

  } catch (error) {
    console.log(error);
  }

  // France Map
  try {

    var vmap4 = $('#vmap4');
    if (vmap4[0]) {
      vmap4.vectorMap({
        map: 'france_fr',
        color: '#007BFF',
        borderColor: '#fff',
        backgroundColor: '#fff',
        enableZoom: true,
        showTooltip: true
      });
    }

  } catch (error) {
    console.log(error);
  }

  // Russia Map
  try {
    var vmap5 = $('#vmap5');
    if (vmap5[0]) {
      vmap5.vectorMap({
        map: 'russia_en',
        color: '#007BFF',
        borderColor: '#fff',
        backgroundColor: '#fff',
        hoverOpacity: 0.7,
        selectedColor: '#999999',
        enableZoom: true,
        showTooltip: true,
        scaleColors: ['#C8EEFF', '#006491'],
        normalizeFunction: 'polynomial'
      });
    }


  } catch (error) {
    console.log(error);
  }

  // Brazil Map
  try {

    var vmap6 = $('#vmap6');
    if (vmap6[0]) {
      vmap6.vectorMap({
        map: 'brazil_br',
        color: '#007BFF',
        borderColor: '#fff',
        backgroundColor: '#fff',
        onRegionClick: function (element, code, region) {
          var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
          alert(message);
        }
      });
    }

  } catch (error) {
    console.log(error);
  }
})(jQuery);
(function ($) {
  // Use Strict
  "use strict";
  try {
    var progressbarSimple = $('.js-progressbar-simple');
    progressbarSimple.each(function () {
      var that = $(this);
      var executed = false;
      $(window).on('load', function () {

        that.waypoint(function () {
          if (!executed) {
            executed = true;
            /*progress bar*/
            that.progressbar({
              update: function (current_percentage, $this) {
                $this.find('.js-value').html(current_percentage + '%');
              }
            });
          }
        }, {
          offset: 'bottom-in-view'
        });

      });
    });
  } catch (err) {
    console.log(err);
  }
})(jQuery);
(function ($) {
  // USE STRICT
  "use strict";

  // Scroll Bar
  try {
    var jscr1 = $('.js-scrollbar1');
    if (jscr1[0]) {
      const ps1 = new PerfectScrollbar('.js-scrollbar1');
    }

    var jscr2 = $('.js-scrollbar2');
    if (jscr2[0]) {
      const ps2 = new PerfectScrollbar('.js-scrollbar2');

    }

  } catch (error) {
    console.log(error);
  }

})(jQuery);
(function ($) {
  // USE STRICT
  "use strict";

  // Select 2
  try {

    $(".js-select2").each(function () {
      $(this).select2({
        minimumResultsForSearch: 20,
        dropdownParent: $(this).next('.dropDownSelect2')
      });
    });

  } catch (error) {
    console.log(error);
  }


})(jQuery);
(function ($) {
  // USE STRICT
  "use strict";

  // Dropdown 
  try {
    var menu = $('.js-item-menu');
    var sub_menu_is_showed = -1;

    for (var i = 0; i < menu.length; i++) {
      $(menu[i]).on('click', function (e) {
        e.preventDefault();
        $('.js-right-sidebar').removeClass("show-sidebar");
        if (jQuery.inArray(this, menu) == sub_menu_is_showed) {
          $(this).toggleClass('show-dropdown');
          sub_menu_is_showed = -1;
        }
        else {
          for (var i = 0; i < menu.length; i++) {
            $(menu[i]).removeClass("show-dropdown");
          }
          $(this).toggleClass('show-dropdown');
          sub_menu_is_showed = jQuery.inArray(this, menu);
        }
      });
    }
    $(".js-item-menu, .js-dropdown").click(function (event) {
      event.stopPropagation();
    });

    $("body,html").on("click", function () {
      for (var i = 0; i < menu.length; i++) {
        menu[i].classList.remove("show-dropdown");
      }
      sub_menu_is_showed = -1;
    });

  } catch (error) {
    console.log(error);
  }

  var wW = $(window).width();
  // Right Sidebar
  var right_sidebar = $('.js-right-sidebar');
  var sidebar_btn = $('.js-sidebar-btn');

  sidebar_btn.on('click', function (e) {
    e.preventDefault();
    for (var i = 0; i < menu.length; i++) {
      menu[i].classList.remove("show-dropdown");
    }
    sub_menu_is_showed = -1;
    right_sidebar.toggleClass("show-sidebar");
  });

  $(".js-right-sidebar, .js-sidebar-btn").click(function (event) {
    event.stopPropagation();
  });

  $("body,html").on("click", function () {
    right_sidebar.removeClass("show-sidebar");

  });


  // Sublist Sidebar
  try {
    var arrow = $('.js-arrow');
    arrow.each(function () {
      var that = $(this);
      that.on('click', function (e) {
        e.preventDefault();
        that.find(".arrow").toggleClass("up");
        that.toggleClass("open");
        that.parent().find('.js-sub-list').slideToggle("250");
      });
    });

  } catch (error) {
    console.log(error);
  }


  try {
    // Hamburger Menu
    $('.hamburger').on('click', function () {
      $(this).toggleClass('is-active');
      $('.navbar-mobile').slideToggle('500');
    });
    $('.navbar-mobile__list li.has-dropdown > a').on('click', function () {
      var dropdown = $(this).siblings('ul.navbar-mobile__dropdown');
      $(this).toggleClass('active');
      $(dropdown).slideToggle('500');
      return false;
    });
  } catch (error) {
    console.log(error);
  }
})(jQuery);
(function ($) {
  // USE STRICT
  "use strict";

  // Load more
  try {
    var list_load = $('.js-list-load');
    if (list_load[0]) {
      list_load.each(function () {
        var that = $(this);
        that.find('.js-load-item').hide();
        var load_btn = that.find('.js-load-btn');
        load_btn.on('click', function (e) {
          $(this).text("Loading...").delay(1500).queue(function (next) {
            $(this).hide();
            that.find(".js-load-item").fadeToggle("slow", 'swing');
          });
          e.preventDefault();
        });
      })

    }
  } catch (error) {
    console.log(error);
  }

})(jQuery);
(function ($) {
  // USE STRICT
  "use strict";

  try {

    $('[data-toggle="tooltip"]').tooltip();

  } catch (error) {
    console.log(error);
  }

  // Chatbox
  try {
    var inbox_wrap = $('.js-inbox');
    var message = $('.au-message__item');
    message.each(function () {
      var that = $(this);

      that.on('click', function () {
        $(this).parent().parent().parent().toggleClass('show-chat-box');
      });
    });


  } catch (error) {
    console.log(error);
  }

})(jQuery);


$.fn.parseForm = function(){
  var serializeObj={};
  var array=this.serializeArray();
  var str=this.serialize();
  $(array).each(function(){
      if(serializeObj[this.name]){
          if($.isArray(serializeObj[this.name])){
              serializeObj[this.name].push(this.value);
          }else{
              serializeObj[this.name]=[serializeObj[this.name],this.value];
          }
      }else{
          serializeObj[this.name]=this.value; 
      }
  });
  return serializeObj;
};

function digitFormatter(digit, target = 'float', decimal = 2,) {
  var d = Number(digit);
  if (target == 'int') {
    return d.toFixed(0);
  }
  else if (target == 'float') {
    return d.toFixed(decimal);
  }
  else if (target == 'percentage') {
    return (d * 100).toFixed(2) + '%';
  }
  else if (target == 'percentage4') {
    return (d * 100).toFixed(4) + '%';
  }
  else if (target == 'CNY') {
    if (Math.abs(digit) > 10 ** 12) {
      return (d / 10 ** 12).toFixed(decimal) + "万亿";
    }
    if (Math.abs(digit) > 10 ** 8) {
      return (d / 10 ** 8).toFixed(decimal) + "亿";
    }
    if (Math.abs(digit) > 10 ** 4) {
      return (d / 10 ** 4).toFixed(decimal) + "万";
    }     
    return d.toFixed(decimal) + "元";
  }
  else if (target == 'CNS') {
    if (digit > 10 ** 8) {
      return (d / 10 ** 8).toFixed(decimal) + "亿";
    }
    else if (digit > 10 ** 4) {
      return (d / 10 ** 4).toFixed(decimal) + "万";
    } else {
      return d.toFixed(decimal);
    }
  }
}


function dyeingFormatter(value) {
  if (value.search(/[1-9]/) < 0) {
    return value;
  } else if (value.indexOf('-') >= 0) {
    return `<span class="text-success">` + value + `</span>`;
  } else {
    return `<span class="text-danger">` + value + `</span>`;
  }
}


var colorList = ['#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'];
var labelFont = 'bold 12px Sans-serif';

var KLineOption = {
  animation: true,
  color: colorList,
  legend: {
      top: 20,
      data: ['日K', 'MA5', 'MA10', 'MA20']
  },
  tooltip: {
      triggerOn: 'none',
      transitionDuration: 0,
      confine: true,
      bordeRadius: 4,
      borderWidth: 1,
      borderColor: '#333',
      backgroundColor: 'rgba(255,255,255,0.9)',
      textStyle: {
          fontSize: 12,
          color: '#333'
      },
      position: function (pos, params, el, elRect, size) {
          var obj = {
              top: 60
          };
          obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
          return obj;
      }
  },
  axisPointer: {
      link: [{
          xAxisIndex: [0, 1]
      }]
  },
  dataZoom: [{
      type: 'slider',
      xAxisIndex: [0, 1],
      realtime: false,
      // start: length < 60 ? 0:100-parseInt(6000/length),
      end: 100,
      top: 65,
      height: 20,
      handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
      handleSize: '120%'
  }, {
      type: 'inside',
      xAxisIndex: [0, 1],
      start: 40,
      end: 70,
      top: 30,
      height: 20
  }],
  xAxis: [{
      type: 'category',
      // data: results.trade_date,
      boundaryGap : false,
      axisLine: { lineStyle: { color: '#777' } },
      axisLabel: {
          formatter: function (value) {
              return echarts.format.formatTime('MM-dd', value);
          }
      },
      min: 'dataMin',
      max: 'dataMax',
      axisPointer: {
          show: true
      }
  }, {
      type: 'category',
      gridIndex: 1,
      // data: results.trade_date,
      scale: true,
      boundaryGap : false,
      splitLine: {show: false},
      axisLabel: {show: false},
      axisTick: {show: false},
      axisLine: { lineStyle: { color: '#777' } },
      splitNumber: 20,
      min: 'dataMin',
      max: 'dataMax',
      axisPointer: {
          type: 'shadow',
          label: {show: false},
          triggerTooltip: true,
          handle: {
              show: true,
              margin: 30,
              color: '#B80C00'
          }
      }
  }],
  yAxis: [{
      scale: true,
      splitNumber: 2,
      axisLine: { lineStyle: { color: '#777' } },
      splitLine: { show: true },
      axisTick: { show: false },
      axisLabel: {
          inside: true,
          formatter: '{value}\n'
      }
  }, {
      scale: true,
      gridIndex: 1,
      splitNumber: 2,
      axisLabel: {show: false},
      axisLine: {show: false},
      axisTick: {show: false},
      splitLine: {show: false}
  }],
  grid: [{
      left: 25,
      right: 25,
      top: 110,
      height: 300
  }, {
      left: 25,
      right: 25,
      height: 100,
      top: 440
  }],
  graphic: [{
      type: 'group',
      left: 'center',
      top: 70,
      width: 300,
      bounding: 'raw',
      children: [{
          id: 'MA5',
          type: 'text',
          style: {fill: colorList[1], font: labelFont},
          left: 0
      }, {
          id: 'MA10',
          type: 'text',
          style: {fill: colorList[2], font: labelFont},
          left: 'center'
      }, {
          id: 'MA20',
          type: 'text',
          style: {fill: colorList[3], font: labelFont},
          right: 0
      }]
  }],
  series: [{
      name: 'Volume',
      type: 'bar',
      xAxisIndex: 1,
      yAxisIndex: 1,
      itemStyle: {
          normal: {
              color: '#7fbe9e'
          },
          emphasis: {
              color: '#140'
          }
      },
      // data: results.vol
  }, {
      type: 'candlestick',
      name: '日K',
      // data: k,
      itemStyle: {
          normal: {
              color: '#ef232a',
              color0: '#14b143',
              borderColor: '#ef232a',
              borderColor0: '#14b143'
          },
          emphasis: {
              color: 'black',
              color0: '#444',
              borderColor: 'black',
              borderColor0: '#444'
          }
      }
  }, {
      name: 'MA5',
      type: 'line',
      // data: results.ma5,
      smooth: true,
      showSymbol: false,
      lineStyle: {
          normal: {
              width: 1
          }
      }
  }, {
      name: 'MA10',
      type: 'line',
      // data: results.ma10,
      smooth: true,
      showSymbol: false,
      lineStyle: {
          normal: {
              width: 1
          }
      }
  }, {
      name: 'MA20',
      type: 'line',
      // data: results.ma20,
      smooth: true,
      showSymbol: false,
      lineStyle: {
          normal: {
              width: 1
          }
      }
  }]
};


function message(content, type = 'success') {
  $("#message-box").hide().html(`
      <div class="alert au-alert-` + type + ` alert-dismissible fade show au-alert m-b-40" role="alert">
                          <i class="zmdi zmdi-` + (type == 'success'? 'check':'close') +  `-circle"></i>
                          <span class="content">` + content + `</span>
                          <button class="close" type="button" data-dismiss="alert" aria-label="Close">
                              <span aria-hidden="true">
                                  <i class="zmdi zmdi-close-circle"></i>
                              </span>
                          </button>
                      </div>
  `).slideDown('slow');
}

function isNum(val) {
  return /^[1-9][0-9]+$/gi;
}


var getFilterArgElem = function () {
  var tag = 'A';
  for (var i = 1; i < 10 ** 5; i ++ ){
      if ($('input[name="param-name"][value="' + (tag + i) + '"]').length == 0) {
          tag += i;
          break;
      }
  }
  return `
      <div class="row filter-arg">
          <div class="col col-md-2">
              <input type="input" class="form-control form-control-sm" name="param-name" value="` + tag + `" placeholder="变量名">
          </div>
          <div class="col col-md-1">
              <a class="h4">=</a>
          </div>
          <div class="col col-md-3">
              <input type="input" class="form-control form-control-sm" name="arg-1" placeholder="常量/变量/值">
          </div>
          <div class="col col-md-2">
              <select class="form-control form-control-sm" tabindex="-1" name="opt">
                  <option value="add">+</option>
                  <option value="sub">-</option>
                  <option value="mult">*</option>
                  <option value="div">/</option>
              </select>
          </div>
          <div class="col col-md-3">
              <input type="input" class="form-control form-control-sm" name="arg-2" placeholder="常量/变量/值">
          </div>
          <div class="col col-md-1">
              <button class="btn btn-sm filter-rm-arg" onclick="$(this).parents('.filter-arg').remove()"><i class="fa fa-times text-danger"></i></button>
          </div>
      </div>
  `;
};
var getFilterConditionElem = function () {
  return `
      <div class="row filter-condition" style="margin-bottom: 0.5rem">
          <div class="col col-md-3">
              <select class="form-control form-control-sm" tabindex="-1" name="logic">
                  <option value="or">或</option>
                  <option value="and">且</option>
              </select>
          </div>
          <div class="col col-md-3">
              <input type="input" class="form-control form-control-sm" name="arg-1" placeholder="常量/变量/值">
          </div>
          <div class="col col-md-2">
              <select class="form-control form-control-sm" tabindex="-1" name="opt">
                  <option value="exact">=</option>
                  <option value="gt">></option>
                  <option value="lt"><</option>
                  <option value="gte">≥</option>
                  <option value="lte">≤</option>
              </select>
          </div>
          <div class="col col-md-3">
              <input type="input" class="form-control form-control-sm" name="arg-2" placeholder="常量/变量/值">
          </div>
          <div class="col col-md-1">
              <button class="btn btn-sm filter-rm-condition" onclick="$(this).parents('.filter-condition').remove(); updateCondition();"><i class="fa fa-times text-danger"></i></button>
          </div>
      </div>
  `;
};


function checkAdvanceFilter(argChoices) {
  var definedNames = [];
  var valid = true;
  $('.filter-arg').each(function (_, ele) {
    var paramName = $(ele).find('input[name="param-name"]').val();
    var arg1 = $(ele).find('input[name="arg-1"]').val();
    var arg2 = $(ele).find('input[name="arg-2"]').val();

    if (!arg1 && !arg2) {
      return;
    }
    
    $(ele).find('input[name="arg-1"],input[name="arg-2"]').each(function (_, arg) {
      var value = $(arg).val();

      if ($.isNumeric(value) || argChoices.indexOf(value) != -1 || definedNames.indexOf(value) != -1) {
        $(arg).removeClass('input-invalid');
      } else {
        $(arg).addClass('input-invalid');
        valid = false;
      }
    });

    if (!paramName || definedNames.indexOf(paramName) != -1 || argChoices.indexOf(paramName) != -1 || $.isNumeric(paramName[0])) {
      $(ele).find('input[name="param-name"]').addClass('input-invalid');
      valid = false;
    } else {
      $(ele).find('input[name="param-name"]').removeClass('input-invalid');
      definedNames.push(paramName);
    }
  });

  $('.filter-condition').each(function (_, ele) {
    var arg1 = $(ele).find('input[name="arg-1"]').val();
    var arg2 = $(ele).find('input[name="arg-2"]').val();

    if (!arg1 && !arg2) {
      return;
    }

    $(ele).find('input[name="arg-1"],input[name="arg-2"]').each(function (_, arg) {
      var value = $(arg).val();

      if ($.isNumeric(value) || argChoices.indexOf(value) != -1 || definedNames.indexOf(value) != -1) {
        $(arg).removeClass('input-invalid');
      } else {
        $(arg).addClass('input-invalid');
        valid = false;
      }
    });
  });
  return valid;
}

function getAdvanceFilter() {
  var filter = {
    variables: [],
    conditions: [],
  };
  
  $('.filter-arg').each(function (_, ele) {
    if ($(ele).find('input[name="arg-1"]').val() && $(ele).find('input[name="arg-2"]').val()) {
      filter.variables.push({
        param: $(ele).find('input[name="param-name"]').val(),
        arg1: $(ele).find('input[name="arg-1"]').val(),
        opt: $(ele).find('select[name="opt"]').val(),
        arg2: $(ele).find('input[name="arg-2"]').val(),
      });
    }
  });

  $('.filter-condition').each(function (_, ele) {
    if ($(ele).find('input[name="arg-1"]').val() && $(ele).find('input[name="arg-2"]').val()) {
      filter.conditions.push({
        logic: $(ele).find('select[name="logic"]').val(),
        arg1: $(ele).find('input[name="arg-1"]').val(),
        opt: $(ele).find('select[name="opt"]').val(),
        arg2: $(ele).find('input[name="arg-2"]').val(),
      });
    }
  });

  return filter;
}

var updateCondition = function () {
  $('.filter-conditions select').removeAttr('disabled');
  $('.filter-conditions select:eq(0)').attr('disabled', '');
}


function saveAdvanceFilter() {
  window.localStorage.setItem('achievement:advancefilter:json', JSON.stringify(getAdvanceFilter()));
}

function loadAdvanceFilter() {
  var storage = window.localStorage.getItem('achievement:advancefilter:json');
  if (storage == null) {
    var filter = {
      variables: [],
      conditions: [],
    }
  } else {
    var filter = JSON.parse(storage);
  }

  for (var i = 0; i < filter.variables.length; i++ ){
    $('.filter-args').append(getFilterArgElem());
    var arg = filter.variables[i];
    $('.filter-arg:eq(' + i + ')').find('input[name="param-name"]').val(arg.param);
    $('.filter-arg:eq(' + i + ')').find('input[name="arg-1"]').val(arg.arg1);
    $('.filter-arg:eq(' + i + ')').find('select[name="opt"]').val(arg.opt);
    $('.filter-arg:eq(' + i + ')').find('input[name="arg-2"]').val(arg.arg2);
  }
  $('.filter-arg').length == 0 && $('.filter-args').append(getFilterArgElem());

  for (var i = 0; i < filter.conditions.length; i++ ){
    $('.filter-conditions').append(getFilterConditionElem());
    var cond = filter.conditions[i];
    $('.filter-condition:eq(' + i + ')').find('select[name="logic"]').val(cond.logic);
    $('.filter-condition:eq(' + i + ')').find('input[name="arg-1"]').val(cond.arg1);
    $('.filter-condition:eq(' + i + ')').find('select[name="opt"]').val(cond.opt);
    $('.filter-condition:eq(' + i + ')').find('input[name="arg-2"]').val(cond.arg2);
  }
  $('.filter-condition').length == 0 && $('.filter-conditions').append(getFilterConditionElem());
  updateCondition();
}


$('[auto-cache-id]').blur(function (event) {
  var inputValue = event.target.value;
  var cacheID = event.target.getAttribute('auto-cache-id');
  window.localStorage.setItem(cacheID, inputValue);
});

$('[auto-cache-id]').each(function (_, elem) {
  var cacheID = elem.getAttribute('auto-cache-id');
  var cachedData = window.localStorage.getItem(cacheID);
  if (cachedData != null) {
    elem.value = cachedData;
  }
})

var searchInputPopover = function() {
  $('.search-input').popover({
      title: 'Tips',
      html: true,
      content: `
          1. 使用 <code>~</code> 符号进行取反（排除）操作<br>
          2. 使用 <code>&</code> 符号进行与操作<br>
          3. 使用 <code>|</code> 符号进行或操作<br>
          4. 符号间优先级为 <code>~</code> > <code>&</code> > <code>|</code>
      `,
      placement: 'top',
      trigger: 'focus',
  });
}


$(document).ready(function(){
  $(document).on('click', '.filter-field', function() {
      var $this = $(this);
      var filterValue = $this.text();
      var $table = $this.closest('table');
      
      if ($this.hasClass('filter-field-active')) {
          $table.find('tbody tr').show().removeClass('filter-field-active');
          $table.find('.filter-field').removeClass('filter-field-active');
      } else {
          $table.find('tbody tr').each(function(){
              var row = $(this);
              var field = row.find('.filter-field');
              if (field.text() != filterValue) {
                  row.hide();
                  field.removeClass('filter-field-active');
              } else {
                  row.show();
                  field.addClass('filter-field-active');
              }
          });
      }
  });
});



$(document).ready(function(){
  var sortTable = function($table, index, ascending) {
      var rows = $table.find('tbody tr').get();
      rows.sort(function(a, b) {
          var A = $(a).children('td').eq(index).text().toUpperCase();
          var B = $(b).children('td').eq(index).text().toUpperCase();
          
          if ($.isNumeric(A) && $.isNumeric(B)) {
              return ascending ? A - B : B - A;
          }

          if (A < B) {
              return ascending ? -1 : 1;
          }
          if (A > B) {
              return ascending ? 1 : -1;
          }
          return 0;
      });

      $.each(rows, function(index, row) {
          $table.children('tbody').append(row);
      });
  };

  $('.sortable-field').click(function() {
      var $this = $(this);
      var $th = $this.closest('.sortable-field');
      var $table = $th.closest('table');
      var index = $th.index();

      if ($this.hasClass('sort-desc')) {
        $this.removeClass('sort-desc')
      } else {
        $this.addClass('sort-desc')
      }

      var ascending = !$this.hasClass('sort-desc');

      sortTable($table, index, ascending);
  });
});


function textOverFlowDisplay(value, row, index, field, length=16) {
  if (value.length < length) {
      return value;
  }
  var subValue = value.substring(0, length) + '...';
  var htmlValue = '';
  var concepts = value.split('/');
  for (var i = 0; i < concepts.length; i++ ) {
      htmlValue += (i + 1) + '. ' + concepts[i] + '<br>';
  }
  return `
  <span class="overflow-text">
      <a href="#" data-toggle="popover" data-html="true" data-title="Concepts" data-trigger="hover" data-content="` + htmlValue + `">
          ` + subValue + `
      </a>
  </span>
  `;
} 

function textOverFlowDisplayDouble(value, row, index, field, length=30) {
  return textOverFlowDisplay(value, row, index, field, length)
}


function exportTable($button) {
  // 获取按钮上指定的table元素
  const tableSelector = $button.attr('data-table');
  if (!tableSelector) {
      console.error('No table selector specified on button');
      return;
  }
  
  const $table = $(tableSelector);
  if ($table.length === 0) {
      console.error('Table not found with selector:', tableSelector);
      return;
  }
  
  // 收集CSV数据
  let csvData = [];
  
  // 处理表头
  $table.find('thead tr').each(function() {
      let rowData = [];
      if ($(this).find('th').length > 0) {
        $(this).find('th').each(function() {
            rowData.push(formatCsvValue($(this).text()));
        });
        csvData.push(rowData.join(','));
      }
      if ($(this).find('td').length > 0) {
        $(this).find('td').each(function() {
            rowData.push(formatCsvValue($(this).text()));
        });
        csvData.push(rowData.join(','));
      }
  });
  
  // 处理表体
  $table.find('tbody tr').each(function() {
      let rowData = [];
      $(this).find('td').each(function() {
          rowData.push(formatCsvValue($(this).text()));
      });
      csvData.push(rowData.join(','));
  });
  
    // 创建CSV文件并下载
    const bom = '\uFEFF'; // UTF-8 BOM
    const csvContent = bom + csvData.join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
  
  // 创建下载链接
  const link = document.createElement('a');
  link.setAttribute('href', url);
  link.setAttribute('download', 'table_export.csv');
  link.style.visibility = 'hidden';
  
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

/**
* 格式化CSV值 - 处理包含逗号或换行符的文本
* @param {string} value - 要格式化的文本
* @returns {string} 格式化后的CSV值
*/
function formatCsvValue(value) {
  if (value.includes(',') || value.includes('\n') || value.includes('"')) {
      return '"' + value.replace(/"/g, '""') + '"';
  }
  return value;
}

// 绑定按钮点击事件
$(document).ready(function() {
  $('button[data-table]').on('click', function() {
      exportTable($(this));
  });
});